<script lang="ts" setup>
  import { onMounted, reactive, ref, watch } from 'vue'
  import appStore from '@/store'
  import { ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { useRouter, useRoute } from 'vue-router'
  import UserService from '@/api/userService'
  import _ from 'lodash'
  import lts from '@/api/lts'
  const router = useRouter()
  const route = useRoute()
  interface optionList {
    value: string
    label: string
  }
  let transferData = reactive({
    data: {
      log_group_id: '',
      log_stream_id: '',
      transfer_info: {
        obs_bucket_name: '',
        obs_period: '',
        obs_transfer_path: ''
      }
    }
  })
  const transferRef = ref<FormInstance>()
  const rules = reactive<FormRules>({
    obs_period_unit: [{ required: true, message: '请选择转储时间单位', trigger: 'blur' }],
    obs_bucket_name: [{ required: true, message: '请输入OBS桶名', trigger: 'blur' }],
    obs_period: [{ required: true, message: '请选择转储周期', trigger: 'blur' }],
    obs_transfer_path: [
      { required: true, message: '输入转储路径前缀', trigger: 'blur' },
      {
        pattern: /^[a-zA-Z0-9-]{1,64}$/,
        message: '请输入正确的转储路径前缀，包含大小写字母、数字与连接符“-”，长度小于64，如：LTS-test',
        trigger: 'blur'
      }
    ]
  })
  let creating = ref(false)
  const onSubmit = async (formEl: FormInstance | undefined) => {
    if (creating.value) return
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        let obj
        const str: string = decodeURIComponent(route.params.idData as string)
        obj = JSON.parse(str)
        let param
        param = JSON.parse(JSON.stringify(transferData.data))
        param.log_group_id = obj.log_group_id
        param.log_stream_id = obj.log_stream_id
        try {
          creating.value = true
          let res = await lts.createTransfer(param)
          if (res.status < 300) {
            creating.value = false
            ElMessage({
              message: '创建成功',
              type: 'success'
            })
            localStorage.removeItem('transferData')
            router.push({ name: 'ltsList' })
          }
        } catch (err) {
          creating.value = false
          ElMessage.error('创建失败')
        }
      } else {
        ElMessage({
          message: '请检查参数',
          type: 'warning'
        })
      }
    })
  }
  const onReset = () => {
    transferData.data = {
      log_group_id: '',
      log_stream_id: '',
      transfer_info: {
        obs_bucket_name: '',
        obs_period: '',
        obs_transfer_path: ''
      }
    }
  }
  watch(
    () => transferData.data,
    (newValue, oldValue) => {
      localStorage.setItem('transferData', JSON.stringify(newValue))
    },
    { deep: true }
  )
  const back = () => {
    router.go(-1)
  }
  onMounted(() => {
    if (localStorage.getItem('transferData')) {
      transferData.data = JSON.parse(localStorage.getItem('transferData') as string)
    }
  })
  interface optionList {
    value: string
    label: string
  }
  const getbucket = {
    project_id: appStore.userStore.project_id,
    region: appStore.userStore.region,
    vpc_id: ''
  }
  const getBucketName = async () => {
    let res = await UserService.getBucket(getbucket)
    if (res.status == 200) {
      res.data.bucket_name.forEach((item: string) => {
        bucket_names.push({
          value: item,
          label: item
        })
      })
    }
  }
  const bucket_names: optionList[] = reactive([])
  const periodOptions: optionList[] = reactive([
    { value: '2min', label: '2分钟' },
    { value: '5min', label: '5分钟' },
    { value: '30min', label: '30分钟' },
    { value: '1hour', label: '1小时' },
    { value: '3hour', label: '3小时' },
    { value: '6hour', label: '6小时' },
    { value: '12hour', label: '12小时' }
  ])
  getBucketName()
</script>
<template>
  <div id="createFleet">
    <div class="create-box">
      <span>新建日志转储</span>
      <span class="back" v-if="appStore.userStore.project_id" @click="back">&lt;&nbsp;返回</span>
    </div>
    <div class="form-box">
      <el-form ref="transferRef" :model="transferData.data" label-width="140px" label-position="left" :inline="true" :rules="rules" class="ac-form">
        <div class="card-box">
          <div class="card-content">
            <el-form-item prop="transfer_info.obs_bucket_name" :rules="rules.obs_bucket_name">
              <template #label>
                <div class="item-label">OBS桶名</div>
              </template>
              <el-select v-model="transferData.data.transfer_info.obs_bucket_name" placeholder="请选择OBS桶名" :validate-event="true" filterable>
                <el-option v-for="item in bucket_names" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item prop="transfer_info.obs_period" :rules="rules.obs_period">
              <template #label>
                <div class="item-label">转储周期</div>
              </template>
              <el-select v-model="transferData.data.transfer_info.obs_period" placeholder="请选择转储周期" :validate-event="true">
                <el-option v-for="item in periodOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item prop="transfer_info.obs_transfer_path" :rules="rules.obs_transfer_path">
              <template #label>
                <div class="item-label">
                  转储路径前缀
                  <el-tooltip effect="dark" content="转储路径为：桶名/LogTank/region/前缀/Y/M/D" placement="right"
                    ><el-icon><QuestionFilled /></el-icon
                  ></el-tooltip>
                </div>
              </template>
              <el-input v-model.trim="transferData.data.transfer_info.obs_transfer_path" maxlength="1024" placeholder="请输入转储路径前缀" />
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div class="operateButton">
        <el-button class="btn button" @click="onReset">重置</el-button>
        <el-button class="btn new button" type="primary" @click="onSubmit(transferRef)">创建</el-button>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
  #createFleet {
    background-color: $blank-color;
    .its_arr {
      display: flex;
      align-items: center;
    }
    .its_arr:not(:last-child) {
      margin-bottom: 10px;
    }
    .icon-outbox {
      display: flex;
    }
    .icon-box {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 28px;
      height: 28px;
      border: 1px solid $border-color;
      margin-left: 10px;
    }
    .create-box {
      height: 60px;
      width: calc(100% - 200px);
      position: absolute;
      top: 50px;
      left: 200px;
      background-color: $blank-color;
      color: $text-color;
      display: flex;
      align-items: center;
      z-index: 1;
      span {
        font-size: 16px;
        font-weight: bold;
        margin-left: 20px;
        margin-right: 10px;
        line-height: 60px;
      }
      .button {
        width: 100px;
        height: 28px;
      }
    }
    .form-box {
      background-color: $blank-color;
      padding: 30px;
      margin-top: 60px;
      .select-box {
        display: flex;
        align-items: center;
        margin-bottom: 30px;
        .select-lable {
          width: 165px;
          color: $text-color;
          font-size: 14px;
          .must {
            color: rgb(245, 108, 108);
            margin-right: 4px;
          }
        }
      }

      .card-box {
        background-color: $blank-color;
        margin-bottom: 36px;
        .card-header {
          display: flex;
          align-items: center;
          height: 14px;
          margin-bottom: 44px;

          .header-bar {
            height: 100%;
            width: 4px;
            background: $main-color;
            margin-right: 6px;
          }
          .header-title {
            height: 100%;
            line-height: 100%;
            color: #1d1d1f;
            font-weight: bold;
            font-size: 14px;
            margin-right: 10px;
          }
        }
      }
      //   .card-box:first-child {
      //     border-bottom: 1px solid $border-color;
      //   }
      .el-form-item {
        width: 50%;
        margin: 0;
        margin-bottom: 30px;

        :deep(.el-form-item__label) {
          width: 165px !important;
        }
        .item-label {
          width: 180px;
          color: $text-color;
          display: flex;
          align-items: center;
          i {
            margin-left: 10px;
          }
        }

        .el-input {
          width: 480px;
          height: 30px;
        }
        .el-select {
          width: 480px;
          height: 30px;
          line-height: 30px;
          :deep(.el-input) {
            height: 30px;
            .el-input__inner {
              height: 30px;
            }
          }
        }
      }
    }
    .operateButton {
      justify-content: center;
      display: flex;
      gap: 20px;
      margin-top: 30px;
      .el-form-item {
        width: 260px;
      }
      .button {
        width: 120px;
        height: 34px;
      }
    }
  }
</style>
